// 存证系统相关的类型定义和工具函数

export interface ProofStorageReq {
  evidences: string[];
}

export interface ProofStorageResp {
  hashs: string[];
}

export interface ProofStatusResp {
  status: string;
}

export interface ProofRecord {
  hash: string;
  evidence: string;
  status: 'pending' | 'confirmed' | 'failed';
  timestamp: number;
  batchId?: string;
}

export interface BatchInfo {
  id: string;
  proofsCount: number;
  status: 'pending' | 'confirmed';
  timestamp: number;
  merkleRoot?: string;
}

export const STORAGE_BASE_URL = "http://localhost:9081/api/v1";

// 检查存证服务器状态
export async function checkStorageServerStatus(baseUrl: string = STORAGE_BASE_URL): Promise<boolean> {
  try {
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 3000);
    
    const response = await fetch(`${baseUrl}/proof/status?hash=test`, {
      signal: controller.signal,
    });
    
    clearTimeout(timeoutId);
    return response.ok || response.status === 404; // 404也表示服务器在运行
  } catch (error) {
    console.warn('存证服务器连接失败:', error);
    return false;
  }
}

// 提交单个存证
export async function submitProofStorage(evidence: string, baseUrl: string = STORAGE_BASE_URL): Promise<ProofStorageResp> {
  const response = await fetch(`${baseUrl}/proof/storage`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      evidences: [evidence]
    } as ProofStorageReq),
  });

  if (!response.ok) {
    const error = await response.text();
    throw new Error(`HTTP ${response.status}: ${error}`);
  }

  const result: ProofStorageResp = await response.json();
  console.log('存证服务器响应:', result);
  
  // 验证响应数据
  if (!result || !result.hashs || !Array.isArray(result.hashs) || result.hashs.length === 0) {
    console.error('无效的服务器响应:', result);
    throw new Error('服务器返回的数据格式错误：缺少存证哈希');
  }

  return result;
}

// 获取存证状态
export async function getProofStatus(hash: string, baseUrl: string = STORAGE_BASE_URL): Promise<ProofStatusResp> {
  const response = await fetch(`${baseUrl}/proof/status?hash=${hash}`);
  
  if (!response.ok) {
    throw new Error(`获取存证状态失败: HTTP ${response.status}`);
  }

  return await response.json();
}

// 等待存证确认
export async function waitForProofConfirmation(
  hash: string,
  onStatusUpdate?: (status: 'confirmed' | 'failed') => void,
  maxRetries: number = 5,
  retryInterval: number = 3000,
  baseUrl: string = STORAGE_BASE_URL
): Promise<boolean> {
  for (let i = 0; i < maxRetries; i++) {
    try {
      await new Promise(resolve => setTimeout(resolve, retryInterval));
      
      const result = await getProofStatus(hash, baseUrl);
      
      if (result.status === 'confirmed') {
        onStatusUpdate?.('confirmed');
        return true;
      }
    } catch (error) {
      console.warn(`检查存证状态失败 (尝试 ${i + 1}/${maxRetries}):`, error);
    }
  }

  // 超时标记为失败
  onStatusUpdate?.('failed');
  return false;
}

// 生成符合业务场景的存证内容
export function generateBusinessEvidence(): string {
  const evidenceTypes = [
    // 理财产品相关
    {
      type: "理财产品购买",
      templates: [
        "客户{客户ID}购买理财产品{产品编号}，金额{金额}万元，期限{期限}个月",
        "理财产品{产品编号}销售记录：客户{客户ID}，投资金额{金额}万元",
        "客户{客户ID}签署理财产品{产品编号}风险确认书，投资金额{金额}万元"
      ]
    },
    // 银行存款相关
    {
      type: "银行存款",
      templates: [
        "客户{客户ID}办理定期存款业务，金额{金额}万元，存期{期限}个月",
        "储蓄账户{账户号}存入资金{金额}万元，操作员{操作员}",
        "客户{客户ID}大额存单购买记录，金额{金额}万元，年利率{利率}%"
      ]
    },
    // 贷款业务相关
    {
      type: "贷款业务",
      templates: [
        "客户{客户ID}申请个人贷款{金额}万元，担保方式：{担保方式}",
        "企业客户{客户ID}授信额度{金额}万元审批通过，用途：{用途}",
        "客户{客户ID}房贷放款{金额}万元，房产地址：{地址}"
      ]
    },
    // 保险业务相关
    {
      type: "保险业务",
      templates: [
        "客户{客户ID}购买保险产品{产品名称}，保额{金额}万元",
        "保险理赔记录：客户{客户ID}，理赔金额{金额}万元，事故类型：{类型}",
        "客户{客户ID}保险续费成功，产品{产品名称}，保费{金额}元"
      ]
    },
    // 基金投资相关
    {
      type: "基金投资",
      templates: [
        "客户{客户ID}申购基金{基金代码}，金额{金额}万元",
        "基金{基金代码}赎回记录：客户{客户ID}，赎回份额{份额}份",
        "客户{客户ID}基金定投设置：{基金代码}，每月{金额}元"
      ]
    },
    // 数字货币相关
    {
      type: "数字货币",
      templates: [
        "数字人民币钱包{钱包ID}充值{金额}元，来源：银行卡{卡号}",
        "数字货币交易记录：从{发送方}转账{金额}元至{接收方}",
        "客户{客户ID}开通数字人民币钱包，初始额度{金额}元"
      ]
    }
  ];

  // 随机选择存证类型
  const evidenceType = evidenceTypes[Math.floor(Math.random() * evidenceTypes.length)];
  const template = evidenceType.templates[Math.floor(Math.random() * evidenceType.templates.length)];

  // 生成随机参数
  const params = {
    客户ID: `C${String(Math.floor(Math.random() * 999999) + 100000)}`,
    产品编号: `P${String(Math.floor(Math.random() * 9999) + 1000)}`,
    产品名称: ["平安福", "太平洋安心保", "华泰综合意外险", "人寿重疾险"][Math.floor(Math.random() * 4)],
    基金代码: `${String(Math.floor(Math.random() * 899999) + 100000)}`,
    账户号: `****${String(Math.floor(Math.random() * 9999) + 1000)}`,
    卡号: `****${String(Math.floor(Math.random() * 9999) + 1000)}`,
    钱包ID: `W${String(Math.floor(Math.random() * 999999) + 100000)}`,
    发送方: `钱包${String(Math.floor(Math.random() * 999) + 100)}`,
    接收方: `钱包${String(Math.floor(Math.random() * 999) + 100)}`,
    金额: String(Math.floor(Math.random() * 500) + 10),
    期限: String([3, 6, 12, 24, 36][Math.floor(Math.random() * 5)]),
    利率: String((Math.random() * 3 + 2).toFixed(2)),
    份额: String(Math.floor(Math.random() * 100000) + 10000),
    操作员: `OP${String(Math.floor(Math.random() * 999) + 100)}`,
    担保方式: ["信用担保", "抵押担保", "质押担保", "保证担保"][Math.floor(Math.random() * 4)],
    用途: ["流动资金", "设备采购", "厂房建设", "技术改造"][Math.floor(Math.random() * 4)],
    地址: ["北京市朝阳区", "上海市浦东新区", "深圳市南山区", "广州市天河区"][Math.floor(Math.random() * 4)] + `某某小区${Math.floor(Math.random() * 99) + 1}号`,
    类型: ["交通事故", "意外伤害", "财产损失", "医疗费用"][Math.floor(Math.random() * 4)]
  };

  // 替换模板中的占位符
  let result = template;
  Object.entries(params).forEach(([key, value]) => {
    result = result.replace(new RegExp(`{${key}}`, 'g'), value);
  });

  return `${new Date().toISOString().split('T')[0]} ${result}`;
}

// 预定义的常见存证内容
export function getCommonEvidenceContent(): string {
  const commonContents = [
    "客户C123456购买理财产品P2024001，投资金额50万元，期限12个月",
    "数字人民币转账记录：从钱包W123456向钱包W789012转账1000元",
    "客户C789012申请个人住房贷款200万元，抵押物：北京市朝阳区住宅",
    "保险理赔审批：客户C456789获得意外险理赔5万元",
    "基金申购记录：客户C234567申购基金159001，金额10万元",
    "大额存单购买：客户C345678存入资金100万元，期限3年",
    "信用卡消费记录：卡号****1234在商户M567890消费2500元",
    "企业授信审批：企业E123456获得信贷额度500万元用于流动资金",
    "保险续费成功：客户C567890续费平安福保险产品，保费8000元",
    "数字货币钱包开通：客户C678901开通数字人民币钱包，初始额度5000元"
  ];

  return commonContents[Math.floor(Math.random() * commonContents.length)];
}

// 模拟批次信息生成
export function generateMockBatches(confirmedProofs: ProofRecord[], batchSize: number = 5): BatchInfo[] {
  if (confirmedProofs.length === 0) return [];

  const batchCount = Math.ceil(confirmedProofs.length / batchSize);
  const batches: BatchInfo[] = [];
  
  for (let i = 0; i < batchCount; i++) {
    batches.push({
      id: `batch-${Date.now()}-${i}`,
      proofsCount: Math.min(batchSize, confirmedProofs.length - i * batchSize),
      status: 'confirmed',
      timestamp: Date.now() - (batchCount - i - 1) * 60000, // 模拟时间间隔
      merkleRoot: `0x${Math.random().toString(16).substr(2, 64)}`, // 模拟merkle根
    });
  }
  
  return batches;
}

// 网络错误检测
export function isNetworkError(error: unknown): boolean {
  return error instanceof TypeError && 
         (error.message.includes('fetch') || error.message.includes('NetworkError'));
}

// 格式化错误消息
export function formatErrorMessage(error: unknown): string {
  if (isNetworkError(error)) {
    return '网络连接失败，请检查存证服务器是否运行在 http://localhost:9081';
  }
  
  return error instanceof Error ? error.message : String(error);
}
